import { Suspense } from 'react'
import { withAuthOption } from 'src/types/route'
import { Redirect } from 'react-router-dom'
import { IRoute } from 'src/types/route'
import MiddleWare from 'src/middlewares'

// Import nprogress
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { RouteConfigComponentProps } from 'react-router-config'

nprogress.configure({
    showSpinner: false
})

/**
 * 路由重定向
 * @date 2021-05-11
 * @param {string} path
 * @returns {any}
 */
function RedirectTo(path: string) {
    return <Redirect to={path} />
}

/**
 * HOC 路由组件、实现路由守卫
 * @date 2021-03-21
 * @param {any} props
 * @returns {any}
 */
export default function withAuth(Component: any, options: withAuthOption = {}) {
    return (props: RouteConfigComponentProps) => {
        let { isDynamic = true } = props.route as IRoute

        try {
            MiddleWare({ props, options })
        } catch (error: any) {
            return RedirectTo(error.message)
        }
        return (
            isDynamic ? (
                <Suspense fallback={<span />}>
                    <Component {...props} />
                </Suspense>
            ) : <Component {...props} />
        )
    }
}
